<?php
/*
 * 分享奖励模块
 * Class ShareReward
 * @author jie
 * creatTime 2017-1-17
 */
class ShareRewardAction extends Action
{
    /**
     * 创建或者保存奖励接口
     * @param null $id /奖励id
     * @param $name /奖励名称
     * @param null $tagIds  /奖励标签
     * @param  $startTime   /开始时间
     * @param  $endTime /结束时间
     * @param int $isShare   /是否基于分享设置,1基于
     * @param int $articleNum   /0单篇文章,1多篇文章
     * @param int $isClue   /是否基于线索设置,1基于
     * @param null $shareRewardJson /基于分享配置
     * @param null $clueRewardJson  /基于线索配置
     */
    public function saveRewardConfig($id=null,$name,$tagIds=null,$startTime,$endTime,$isShare=0,$articleNum=0,
                                     $isClue=0, $shareRewardJson=null,$clueRewardJson=null)
    {
        $retVal = Session::init();
        if(!$retVal){
            Output::instance()->resultCode(code_access_denied);
            return;
        }
        $cid = Session::$user['customerId'];
        Session::switchCustomer(0);
        $shareReward_tab = M('share_reward');
        $shareRewardSet_tab = M('share_reward_set');
        $rewardTag_tab = M('share_reward_tag_relation');
        Session::switchCustomer($cid);
        if($shareRewardJson == null && $clueRewardJson == null){
            Output::instance()->object([
                'code'=>-1,
                'msg'=>'基于分享与基于线索设置详情二者不同同时为空',
                'results'=>[]
            ]);
            return;
        }
        $data = [];
        if($shareRewardJson !== null){
            $shareRewardJson = json_decode($shareRewardJson, true);
        }
        $clueRewardCfg = [];
        if($clueRewardJson !== null){
            $clueRewardCfg = json_decode($clueRewardJson, true);
        }
        //基于线索保存到share_reward表中
        $data['clueShareRemainder'] = $clueRewardCfg[0]['clueShareRemainder'];
        $data['clueRewardType'] = $clueRewardCfg[0]['clueRewardType'];
        if($clueRewardCfg[0]['clueRewardType'] == 1){
            $data['clueBlessings'] = $clueRewardCfg[0]['clueBlessings'];
            $data['clueGiftName'] = '';
            $data['clueRedMoney'] = $clueRewardCfg[0]['clueRedMoney'];
            $data['clueRewardImgs'] = '';
        }else{
            $data['clueBlessings'] = '';
            $data['clueGiftName'] = $clueRewardCfg[0]['clueGiftName'];
            $data['clueRedMoney'] = 0;
            $data['clueRewardImgs'] = $clueRewardCfg[0]['clueRewardImgs'];
        }


        $data['isShare'] = $isShare;
        $data['isClue'] = $isClue;
        $data['startTime'] = $startTime;
        $data['endTime'] = $endTime;
        $data['name'] = $name;
        $data['cid'] = $cid;
        $data['articleNum'] = $articleNum;
        $ret = false;
        $retId = 0;
        M()->startTrans();
        if(!$id){
            $data['createTime'] = date('Y-m-d H:i:s');
            $data['updateTime'] = date('Y-m-d H:i:s');
            $retId = $shareReward_tab->add($data);
        }else{
            $data['updateTime'] = date('Y-m-d H:i:s');
            $ret = $shareReward_tab->where(['id'=>$id])->save($data);
        }
        if(($id&& !is_numeric($ret)) && !$retId){
            Log::write('保存奖励失败'.$shareReward_tab->getLastSql());
            M()->rollback();
            Output::instance()->object([
                'code'=>-1,
                'msg'=>'保存失败',
                'results'=>[]
            ]);
            return;
        }
        if(!$id){
            $isId = 0;
            $id = $retId;
        }
        //基于分享浏览人数奖励配置存表share_reward_set中
        $shareRewardSet_tab->where(['cid'=>$cid,'rewardId'=>$id])->save(['deleted'=>1]);
        if($isShare){
            $rewardSql = "INSERT INTO `wx_share_reward_set` (`cid`, `rewardId`, `visitCount`, `rewardGrade`, `shareRemainder`,
`rewardType`, `blessings`, `clueGiftName`, `redMoney`, `rewardImgs`, `createTime`) VALUES ";
            foreach ($shareRewardJson as $k => $v) {
                if(empty($v['redMoney'])){
                    $v['redMoney'] = 0.00;
                }
                $rewardSql .= "(".$cid.", ".$id.", ".$v['visitCount'].", ".$v['rewardGrade'].", ".$v['shareRemainder'].",
                 ".$v['rewardType'].", '".$v['blessings']."', '".$v['clueGiftName']."', ".$v['redMoney'].",
                 '".$v['rewardImgs']."', '".date('Y-m-d H:i:s')."'),";
            }
            $rewardSql = trim($rewardSql, ',') . ';';
            $tagRet = M()->execute($rewardSql);
            if(!$tagRet){
                Log::write('保存奖励等级详情失败cid:'.$cid.'|sql:'.M()->getLastSql());
                M()->rollback();
                Output::instance()->object([
                   'code'=>-1,
                   'msg'=>'保存失败',
                   'results'=>[]
                ]);
                return;
            }
        }

        //保存标签
        if($tagIds){
            $rewardTag_tab->where(['cid'=>$cid,'rewardId'=>$id])->delete();
            $tagArr = explode(',',$tagIds);
            $tagData = [];
            $tagData['cid'] = $cid;
            $tagData['rewardId'] = $id;
            $sql = 'insert into wx_share_reward_tag_relation (`cid`,`tagId`,`rewardId`,`createTime`) VALUES ';
            foreach ($tagArr as $key => $val) {
                $sql .= "(" . $cid . "," . $val . "," . $id . ",'" . date('Y-m-d H:i:s') . "'),";
            }
            $sql = trim($sql, ',') . ';';
            $tagRet = M()->execute($sql);
            if(!$tagRet){
                Log::write('保存奖励标签关联失败'.M()->getLastSql());
                M()->rollback();
                Output::instance()->object([
                    'code'=>-1,
                    'msg'=>'保存失败',
                    'results'=>[]
                ]);
                return;
            }
        }
        M()->commit();
        $lastSql = $shareReward_tab->getLastSql();
        if (!$isId) {
            R('Log/add',array('shareReward', '', '分享奖励', op_add, $lastSql, '添加分享奖励：' . $name));
        } else {
            R('Log/add',array('shareReward', '', '分享奖励', op_update, $lastSql, '修改分享奖励：' . $name));
        }
        Output::instance()->object([
           'code'=>0,
           'msg'=>'保存成功',
           'result'=>[
               'id'=>$id
           ]
        ]);
    }

    /**
     * 删除一个奖励
     * @param $id /奖励id
     */
    public function delRewardConfig($id)
    {
        $retVal = Session::init();
        if(!$retVal){
            Output::instance()->resultCode(code_access_denied);
            return;
        }
        $cid = Session::$user['customerId'];
        Session::switchCustomer(0);
        $shareReward_tab = M('share_reward');
        $shareRewardSet_tab = M('share_reward_set');
        Session::switchCustomer($cid);
        $data = [];
        $data['id'] = htmlspecialchars($id);
        $data['deleted'] = 1;
        $rewardCfg = $shareReward_tab->where(['id'=>$id])->find();
        M()->startTrans();
        $ret = $shareReward_tab->where(['id'=>$id])->save($data);
        if(!is_numeric($ret)){
            Log::write('奖励删除失败'.$shareReward_tab->getLastSql());
            Output::instance()->object([
               'code'=>-1,
               'msg'=>'删除失败',
               'results'=>[]
            ]);
            return;
        }
        if($rewardCfg['isShare']){
            $shareDelRet = $shareRewardSet_tab->where(['rewardId'=>$id,'cid'=>$cid])->save(['deleted'=>1]);
            if(!is_numeric($shareDelRet)){
                Log::write('删除奖励等级配置失败cid:'.$cid.'|sql:'.$shareRewardSet_tab->getLastSql());
                M()->rollback();
                Output::instance()->object([
                   'code'=>-1,
                   'msg'=>'删除失败',
                   'results'=>[]
                ]);
                return;
            }
        }
        M()->commit();
        $sql = $shareReward_tab->getLastSql();
        $name = $shareReward_tab->where(['id'=>$id])->getField('name');
        R('Log/add',array('shareReward', '', '分享奖励', op_delete, $sql, '删除分享奖励：' . $name));
        Output::instance()->object([
            'code'=>0,
            'msg'=>'删除成功',
            'results'=>[]
        ]);
    }

    /**
     * 获取单条奖励详情
     * @param $rewardId /奖励id
     */
    public function getRewardDetail($rewardId)
    {
        $retVal = Session::init();
        if(!$retVal){
            Output::instance()->resultCode(code_access_denied);
            return;
        }
        $cid = Session::$user['customerId'];
        Session::switchCustomer(0);
        $shareReward_tab = M('share_reward');
        $shareRewardSet_tab = M('share_reward_set');
        Session::switchCustomer($cid);

        //$rewardInfo = $shareReward_tab->where(['id'=>$rewardId])->find();
        $rewardInfo = $shareReward_tab->alias('a')
            ->join('wx_share_reward_tag_relation b on a.id=b.rewardId')
            ->join('wx_share_reward_tag c on c.id=b.tagId')
            ->field('a.*,GROUP_CONCAT(c.id) as tagIds,GROUP_CONCAT(c.tagName) as tagNames')
            ->where(['a.id'=>$rewardId,'a.deleted'=>0])
            ->group('a.id')
            ->find();
        //var_dump($shareReward_tab->getLastSql());exit;
        if($rewardInfo == null){
            Log::write('查询奖励详情失败cid:'.$cid.'|sql:'.$shareReward_tab->getLastSql());
            Output::instance()->object([
                'code'=>-1,
                'msg'=>'查询失败',
                'results'=>[]
            ]);
            return;
        }
        $rewardInfo['startTime'] = date('Y-m-d', strtotime($rewardInfo['startTime']));
        $rewardInfo['endTime'] = date('Y-m-d', strtotime($rewardInfo['endTime']));
        $shareRewardCfg = $clueRewardJson = [];
        if($rewardInfo['isShare']){
            //查询基于分享浏览人数详情配置
            $shareRewardCfg = $shareRewardSet_tab->where(['cid'=>$cid,'rewardId'=>$rewardId,'deleted'=>0])->select();
        }
        $rewardInfo['shareRewardJson'] = $shareRewardCfg;
        $clueRewardJson[]['clueShareRemainder'] = $rewardInfo['clueShareRemainder'];
        $clueRewardJson[]['clueRewardType'] = $rewardInfo['clueRewardType'];
        $clueRewardJson[]['clueBlessings'] = $rewardInfo['clueBlessings'];
        $clueRewardJson[]['clueGiftName'] = $rewardInfo['clueGiftName'];
        $clueRewardJson[]['clueRedMoney'] = $rewardInfo['clueRedMoney'];
        $clueRewardJson[]['clueRewardImgs'] = $rewardInfo['clueRewardImgs'];
        if($rewardInfo['clueRewardJson']){
            $rewardInfo['clueRewardJson'] = $clueRewardJson;
        }
        Output::instance()->object([
            'code'=>0,
            'msg'=>'ok',
            'results'=>$rewardInfo
        ]);
    }

    /**
     * 获取奖励配置列表
     * @param null $search  /奖励名称
     * @param null $tagId   /标签id
     * @param int $start    /分页开始
     * @param int $limit    /分页偏移量
     * @param string $order /排序
     * @param string $by
     */
    public function getRewardConfigList($search=null,$tagId=null,$start=0,$limit=10,$order='createTime',$by='desc')
    {
        $retVal = Session::init();
        if(!$retVal){
            Output::instance()->resultCode(code_access_denied);
            return;
        }

        $cid = Session::$user['customerId'];
        Session::switchCustomer(0);
        $shareReward_tab = M('share_reward');
        Session::switchCustomer($cid);
        $map = [];
        if($search){
            $map['a.name'] = ['like', '%'.$search.'%'];
        }
        if($tagId){
            $map['c.id'] = $tagId;
        }
        $map['a.cid'] = $cid;
        $map['a.deleted'] = 0;
        $rewardList = $shareReward_tab->alias('a')
            ->join('wx_share_reward_tag_relation b on a.id=b.rewardId')
            ->join('wx_share_reward_tag c on c.id=b.tagId')
            ->field('a.*,GROUP_CONCAT(c.tagName) as tagNames')
            ->where($map)
            ->limit($start, $limit)
            ->group('a.id')
            ->order('a.'.$order.' '.$by)
            ->select();
        if($rewardList == null){
            Log::write('奖励列表为空cid:'.$cid.'|sql:'.$shareReward_tab->getLastSql());
            Output::instance()->object([
                'code'=>-1,
                'msg'=>'暂无奖励',
                'results'=>[]
            ]);
            return;
        }
        $rewardIds = array_column($rewardList, 'id');
        $rewardIds = implode(',',$rewardIds);
        $rewardGradeList = $shareReward_tab->alias('a')
            ->join('wx_share_reward_set d on d.rewardId=a.id and d.deleted=0')
            ->field('a.id,count(d.id) as rewardGrade, sum(d.shareRemainder) as shareRemainder')
            ->where(['id in '.$rewardIds])
            ->group('a.id')
            ->select();
        $rewardGradeLists = [];
        foreach($rewardGradeList as $key=>$val){
            $rewardGradeLists[$val['id']] = $val;
        }
        if($rewardList == null){
            Log::write('奖励列表为空cid:'.$cid.'|sql:'.$shareReward_tab->getLastSql());
            Output::instance()->object([
                'code'=>-1,
                'msg'=>'暂无奖励',
                'results'=>[]
            ]);
            return;
        }
        //var_dump($rewardList);exit;
        foreach($rewardList as $k=>$val){
            $val['rewardGrade'] = $rewardGradeLists[$val['id']]['rewardGrade']?$rewardGradeLists[$val['id']]['rewardGrade']:1;
            if($val['isShare'] and $val['isClue']){
                $val['shareRemainder'] = $rewardGradeLists[$val['id']]['shareRemainder'].'/'.$val['clueShareRemainder'];
            }else if($val['isClue']){
                $val['shareRemainder'] = $val['clueShareRemainder'];
                $val['rewardGrade'] = 1;    //奖励等级
            }else{
                $val['shareRemainder'] = $rewardGradeLists[$val['id']]['shareRemainder'];
            }
            $rewardList[$k] = $val;
        }
        $total = $shareReward_tab->alias('a')
            ->join('wx_share_reward_tag_relation b on a.id=b.rewardId')
            ->join('wx_share_reward_tag c on c.id=b.tagId')
            ->where($map)
            ->field('GROUP_CONCAT(c.tagName) as tagNames')
            ->group('a.id')
            ->select();
        $total = count($total);
        Output::instance()->object([
           'code'=>0,
           'total'=>$total,
           'results'=>$rewardList
        ]);
    }

    /**
     * 获取标签列表
     */
    public function getShareRewardTag()
    {
        $retVal = Session::init();
        if(!$retVal){
            Output::instance()->resultCode(code_access_denied);
            return;
        }

        $cid = Session::$user['customerId'];
        Session::switchCustomer(0);
        $rewardTag_tab = M('share_reward_tag');
        Session::switchCustomer($cid);
        $rewardTagList = $rewardTag_tab->where(['cid'=>$cid,'deleted'=>0])->select();
        if($rewardTagList == null){
            Output::instance()->object([
                'code'=>-1,
                'msg'=>'暂无标签',
                'results'=>[]
            ]);
            return;
        }
        Output::instance()->object([
           'code'=>0,
           'msg'=>'ok',
           'results'=>$rewardTagList
        ]);
    }

    /**
     * 删除奖励标签id
     * @param $id /奖励标签id
     */
    public function delRewardTag($id)
    {
        $retVal = Session::init();
        if(!$retVal){
            Output::instance()->resultCode(code_access_denied);
            return;
        }
        $cid = Session::$user['customerId'];
        Session::switchCustomer(0);
        $rewardTag_tab = M('share_reward_tag');
        Session::switchCustomer($cid);
        $delRet = $rewardTag_tab->where(['id'=>$id])->save(['deleted'=>1]);
        if(!is_numeric($delRet)){
            Output::instance()->object([
                'code'=>-1,
                'msg'=>'删除失败',
                'results'=>[]
            ]);
            return;
        }
        Output::instance()->object([
            'code'=>0,
            'msg'=>'ok',
            'results'=>[]
        ]);
    }
    /**
     * 创建或者更新奖励标签
     * @param null $id  /标签id
     * @param null $tagName /标签名
     */
    public function saveShareRewardTag($id=null,$tagName)
    {
        $retVal = Session::init();
        if(!$retVal){
            Output::instance()->resultCode(code_access_denied);
            return;
        }

        $cid = Session::$user['customerId'];
        Session::switchCustomer(0);
        $shareRewardTag_tab = M('share_reward_tag');
        Session::switchCustomer($cid);
        $data = [];
        $data['cid'] = $cid;
        $data['tagName'] = htmlspecialchars($tagName);
        $retId = $retSave = '';
        if(!$id){
            $data['createTime'] = date('Y-m-d H:i:s');
            $retId = $shareRewardTag_tab->add($data);
        }else{
            $retSave = $shareRewardTag_tab->where(['id'=>$id])->save($data);
        }

        if(($id && !is_numeric($retSave)) && !$retId){
            Log::write('奖励标签创建失败'.$shareRewardTag_tab->getLastSql());
            Output::instance()->object([
                'code'=>-1,
                'msg'=>'提价失败',
                'result'=>[]
            ]);
            return;
        }
        Output::instance()->object([
           'code'=>0,
           'msg'=>'提交成功',
           'results'=>[]
        ]);
    }

    /**
     * 获取单条奖励的中奖详情列表
     * @param $rewardId /奖励id
     * @param null $search  /搜索条件 昵称/姓名
     * @param null $moduleId  //奖励关联的模块id
     * @param int $start    /分页
     * @param int $limit
     * @param string $order /排序
     * @param string $by
     * @param string $excel /0返回1导Excel
     */
    public function getShareRewardList($rewardId,$moduleId=null,$search=null,$start=0,$limit=10,$order='createTime',$by='desc',$excel=0)
    {
        $retVal = Session::init();
        if(!$retVal){
            Output::instance()->resultCode(code_access_denied);
            return;
        }
        $cid = Session::$user['customerId'];
        Session::switchCustomer(0);
        $shareRewardRet_tab = M('share_reward_result');
        Session::switchCustomer($cid);
        $map = [];
        if($search){
            $map['b.nickname|a.fullName'] = ['like', '%'.$search.'%'];
        }
        $map['a.cid'] = $cid;
        $map['a.rewardId'] = $rewardId;
        if($moduleId){
            $map['a.moduleId'] = $moduleId;
            $map['a.module'] = 'micontent';
        }
        if($excel){
            $rewardRetList = $shareRewardRet_tab->alias('a')
                ->join('wx_'.$cid.'_user_weixin_info b on a.uid=b.userId')
                ->join('wx_'.$cid.'_user c on a.uid=c.id')
                //->join('inner join wx_share_reward_visit_result d on d.rewardId=a.rewardId and a.uid=d.uid')
                ->field('a.*,b.nickname,b.headimgurl,c.phone as userPhone,c.fullName as userFullName')
                ->where($map)
                ->order('a.'.$order.' '.$by)
                ->select();
        }else{
            $rewardRetList = $shareRewardRet_tab->alias('a')
                ->join('wx_'.$cid.'_user_weixin_info b on a.uid=b.userId')
                ->join('wx_'.$cid.'_user c on a.uid=c.id')
                ->field('a.*,b.nickname,b.headimgurl,c.phone as userPhone,c.fullName as userFullName')
                ->where($map)
                ->order('a.'.$order.' '.$by)
                ->limit($start, $limit)
                ->select();
        }

        //echo $shareRewardRet_tab->getLastSql();exit;
        if($rewardRetList == null){
            Log::write('暂无奖励cid:'.$cid.'|sql:'.$shareRewardRet_tab->getLastSql());
            Output::instance()->object([
                'code'=>-1,
                'msg'=>'暂无数据',
                'results'=>[]
            ]);
            return;
        }
        foreach($rewardRetList as $k=>$v){
            $v['statusNum'] = $v['status'];
            $v['contactInfo'] = '';
            switch($v['rewardWay']){
                case 1:
                    $v['rewardWay'] = '红包';
                    $rewardCfg = json_decode($v['rewardJson'], true);
                    if($v['rewardCause'] == 1){
                        if(!$v['status']){
                            $v['status'] = '待发放'.$rewardCfg['redMoney'].'元';
                        }else{
                            $v['status'] = '已发放'.$rewardCfg['redMoney'].'元';
                        }
                    }else{
                        if(!$v['status']){
                            $v['status'] = '待发放'.$rewardCfg['clueRedMoney'].'元';
                        }else{
                            $v['status'] = '已发放'.$rewardCfg['clueRedMoney'].'元';
                        }
                    }
                    $v['contactInfo'] = '';
                    if($v['userFullName'] && $v['userPhone']){
                        $v['contactInfo'] = '姓名:'.$v['userFullName'].'|手机:'.$v['userPhone'];
                    }elseif($v['userFullName']){
                        $v['contactInfo'] = '姓名:'.$v['userFullName'];
                    }elseif($v['userPhone']){
                        $v['contactInfo'] = '手机:'.$v['userPhone'];
                    }
                    break;
                case 2:
                    if($v['status']){
                        $v['status'] = '已发放';
                    }else{
                        $v['status'] = '待发放';
                    }
                    $v['rewardWay'] = '实物礼品';
                    $v['contactInfo'] = '';
                    if($v['fullName'] && $v['phone']){
                        $v['contactInfo'] = '姓名:'.$v['fullName'].'|手机:'.$v['phone'].'|地址:'.$v['province'].$v['city'].$v['address'];
                    }
                    break;
                case 3:
                    if($v['status']){
                        $v['status'] = '已发放';
                    }else{
                        $v['status'] = '待发放';
                    }
                    $v['contactInfo'] = '';
                    if($v['fullName'] && $v['phone']){
                        $v['contactInfo'] = '姓名:'.$v['fullName'].'|手机:'.$v['phone'];
                    }
                    $v['rewardWay'] = '虚拟礼品';
                    break;
            }
            switch($v['rewardCause']){
                case 1:
                    $v['rewardCause'] = '分享浏览人数达标';
                    break;
                case 2:
                    $v['rewardCause'] = '线索人数达标';
                    break;
            };
            if($v['rewardJson']){
                $v['rewardJson'] = json_decode($v['rewardJson'], true);
            }
            $rewardRetList[$k] = $v;
        }
        if(!$excel){
            $total = $shareRewardRet_tab->alias('a')
                ->join('wx_'.$cid.'_user_weixin_info b on a.uid=b.userId')
                ->join('wx_'.$cid.'_user c on a.uid=c.id')
                ->field('a.id')
                ->where($map)
                ->count();
            Output::instance()->object([
                'code'=>0,
                'total'=>$total,
                'results'=>$rewardRetList
            ]);
        }else{
            $excelDate = $excelArr = [];
            foreach($rewardRetList as $key=>$val){
                $excelDate['nickname'] = $val['nickname'];
                $excelDate['rewardCause'] = $val['rewardCause'];
                $excelDate['rewardWay'] = $val['rewardWay'];
                $excelDate['shareVisitNum'] = $val['shareVisitNum'];
                $excelDate['contactInfo'] = $val['contactInfo'];
                $excelDate['status'] = $val['status'];
                $excelDate['userFullName'] = $val['userFullName'];
                $excelArr[] = $excelDate;
            }
            $excelFileName = $rewardRetList[0]['rewardName'].'获奖名单'.date('Y-m-d H:i:s');
            $excelCellName = [
              ['userFullName','昵称'],
              ['rewardCause','奖励原因'],
              ['rewardWay','奖励方式'],
              ['shareVisitNum','分享浏览人数'],
              ['contactInfo','联系方式'],
              ['status','状态']
            ];
            Output::instance()->objArrayExcel($excelFileName,$excelCellName,$excelArr);
        }
    }

    /**
     * 手动发送红包或实物或虚拟奖励
     * @param $rewardId /奖励id
     */
    public function updateRewardStatus($rewardId)
    {
        $retVal = Session::init();
        if(!$retVal){
            Output::instance()->resultCode(code_access_denied);
            return;
        }
        $cid = Session::$user['customerId'];
        $user_tab = M('user');
        $template_tab = M('template_messages');
        Session::switchCustomer(0);
        $shareRewardRet = M('share_reward_result');
        $shareRewardVisit_tab = M('share_reward_visit_result');
        $CustomerMallSettingModel = D('customer_mall_setting');
        $cutomerUser_tab = M('customer_user');
        Session::switchCustomer($cid);
        $rewardInfo = $shareRewardRet->where(['id'=>$rewardId])->find();
        $rewardCfgJson = json_decode($rewardInfo['rewardJson'], true);
        if($rewardCfgJson['articleNum']){   //分享奖励基于多篇文章
            $visitRet = $shareRewardVisit_tab->where(['cid'=>$cid,'module'=>'micontent','rewardId'=>$rewardInfo['rewardId'],
                'uid'=>$rewardInfo['uid']])->getField('sum(visitCount)');
        }else{
            $visitRet = $shareRewardVisit_tab->where(['cid'=>$cid,'module'=>'micontent','moduleId'=>$rewardInfo['moduleId'],
                'rewardId'=>$rewardInfo['rewardId'],'uid'=>$rewardInfo['uid']])->getField('visitCount');
        }
        if(!$visitRet){
            Log::write('分享奖励产生浏览数有误cid:'.$cid.'|sql:'.$shareRewardVisit_tab->getLastSql());
        }
        if($rewardId == null){
            Log::write('非法发送奖励cid:'.$cid.'|sql:'.$shareRewardRet->getLastSql());
            Output::instance()->object([
                'code'=>-1,
                'msg'=>'奖励不存在',
                'results'=>[]
            ]);
            return;
        }
        if($rewardInfo['rewardWay'] == 2 || $rewardInfo['rewardWay'] == 3){
            if(empty($rewardInfo['fullName']) || empty($rewardInfo['phone'])){
                Output::instance()->object([
                    'code'=>-1,
                    'msg'=>'用户尚未提交领取信息',
                    'results'=>[]
                ]);
                return;
            }
        }

        M()->startTrans();
        $retSave = $shareRewardRet->where(['id'=>$rewardId])->save(['status'=>1,'grantTime'=>date('Y-m-d H:i:s')]);
        if(!is_numeric($retSave)){
            M()->rollback();
            Log::write('奖励模块手动发奖失败cid:'.$cid.'|sql:'.$shareRewardRet->getLastSql());
            Output::instance()->object([
                'code'=>-1,
                'msg'=>'提交失败',
                'results'=>[]
            ]);
            return;
        }
        $userInfo = $user_tab->alias('a')
            ->join('wx_'.$cid.'_user_weixin_info b on a.id=b.userId')
            ->where(['a.id'=>$rewardInfo['uid']])
            ->field('a.userName, b.nickname')
            ->find();
        $giftName = $rewardCfgJson['clueGiftName'];
        if($rewardInfo['rewardWay'] == 1){
            //TODO 如果是红包奖励,发送红包
            $rewardMoney = $rewardCfgJson['redMoney'];
            $blessings = $rewardCfgJson['blessings'];
            if($rewardCfgJson['isClue']){
                $rewardMoney = $rewardCfgJson['clueRedMoney'];
                $blessings = $rewardCfgJson['clueBlessings'];
            }
            $mediaInfo = WeixinApi::getCustomer($cid);
            if(!$mediaInfo['mode'] && !$mediaInfo['grantStatus']){
                $mediaInfo['nick_name'] = $cutomerUser_tab->where(['customerId'=>$cid, 'agent'=>'business'])->getField('fullName');
            }
            if(strlen($mediaInfo['nick_name']) > 32){
                $mediaInfo['nick_name'] = mb_substr($mediaInfo['nick_name'], 0, 9, 'utf-8').'...';
            }
            $wxPayInfo = $CustomerMallSettingModel->where(['customerId'=>$cid])->find();
            $partnerkey = '';
            $mch_id = '';
            $wxappid = '';
            if($wxPayInfo){
                $partnerkey = $wxPayInfo['payKey'];
                $mch_id = $wxPayInfo['mchId'];
                $wxappid = $wxPayInfo['appId'];
            }
            $sendRet = WeixinApi::sendRedEnvelopeByOpenId($mediaInfo['nick_name'],$userInfo['userName'],$rewardMoney,$blessings,
                false,$partnerkey,$mch_id,$wxappid);
            if(!$sendRet){
                Log::write('红包发送失败:cid'.$cid.'|mallName:'.$mediaInfo['nick_name'].'|userName:'.$userInfo['userName'].'
                |money:'.$rewardMoney.'|partnerkey:'.$partnerkey.'|mch_id:'.$mch_id.'|wxappid:'.$wxappid.'|sql:'.$user_tab->getLastSql());
                M()->rollback();
                Output::instance()->object([
                    'code'=>-1,
                    'msg'=>'发送红包失败',
                    'results'=>[]
                ]);
                return;
            }
            $giftName = '红包奖励'.$rewardMoney.'元';
        }
        M()->commit();
        //TODO 推送模板消息
        $templateId = $template_tab->where(['status'=>'shareRewardConfirm'])->getField('templateId');
        $customer = WeixinApi::getCustomer();
        if($customer['mode']&&$customer['grantStatus']){
            $domainName = $customer["appid"];
            $http['RESOURCEURL']="http://".$domainName.".".C('NEWSERVER_HOST');
        }else{
            $http['RESOURCEURL'] = C("SERVER_HOST");
        }
        $urls = $http['RESOURCEURL']."call.html?customerId=".$cid."&module=micontent&method=getRewardInfo&params=%7B%22micontentId%22%3A%22".$rewardInfo['moduleId']."%22%2C%22rewardId%22%3A%22".$rewardInfo['rewardId']."%22%7D";
        $data['first'] = array('value'=> '您的奖励已发放','color'=>"#743A3A");
        $data['keyword1'] = array('value'=> $userInfo['nickname'],'color'=>'#173177');	//领取人
        $data['keyword2'] = array('value'=> $giftName,'color'=>'#173177');					//奖品
        $data['keyword3'] = array('value'=> date('Y-m-d'),'color'=>'#173177');					//领取时间
        $data['remark'] = array('value'=>'点击查看奖励详情',"color"=>'#008000');
        $url = urlencode($urls);
        $topcolor = "#FF0000";
        WeixinApi::sendTpl($userInfo['userName'], $templateId, $url,$topcolor,$data,true,$cid);

        Output::instance()->object([
           'code'=>0,
           'msg'=>'提交成功',
           'results'=>[]
        ]);
    }

    /**
     * 当产生浏览记录时,生成分享奖励结果
     * @param $moduleId	    //关联奖励的模块id
     * @param $cid	        //cid
     * @param $rewardId		//奖励id
     * @param $miUid		//分享人uid
     * @param $currentUid		//当前浏览人uid
     * @param $rewardCfg	//奖励配置
     * @return bool
     */
    public function saveRewardRet($moduleId,$cid,$rewardId,$rewardCfg,$miUid,$currentUid)
    {
        Session::switchCustomer(0);
        $shareRewardRet = M('share_reward_result');
        $shareReward_tab = M('share_reward');
        $shareRewardSet_tab = M('share_reward_set');
        $shareVisit_tab = M('mishare_visit');
        $shareRewardVisit_tab = M('share_reward_visit_result');
        Session::switchCustomer($cid);
        $TemplateModel = M("template_messages");
        $visitMap = [];
        $visitMap['module'] = 'micontent';
        $visitMap['cid'] = $cid;
        $visitMap['miUid'] = $miUid;
        $visitMap['uId'] = $currentUid;
        $visitMap['moduleId'] = $moduleId;
        $visitMap['createTime']  = [['egt',$rewardCfg['startTime']],['elt',$rewardCfg['endTime']],'and'];
        //分享人在奖励浏览结果表中是否存在记录
        $rewardVisitRet = $shareRewardVisit_tab->where(['rewardId'=>$rewardId,'cid'=>$cid,'moduleId'=>$moduleId, 'uid'=>$miUid,
            'module'=>'micontent'])->find();
        if($rewardVisitRet !== null){
            //判断当前用户对此分享人分享的此篇文章是否已经存在记录,存在时访问结果表不自加一,否则自加一
            $visitRetCount = $shareVisit_tab->where($visitMap)->count('id');
            Log::write('浏览数1111:'.$cid.'|sql:'.$shareVisit_tab->getLastSql());
            if($visitRetCount == 1){
                Log::write('浏览数3333');
                //Log::write('无访问数据cid:'.$cid.'|uid:'.$currentUid.'|miuid:'.$miUid.'|moduleId'.$moduleId);
                $updateVisitRet = $shareRewardVisit_tab->where(['id'=>$rewardVisitRet['id']])->setInc('visitCount');
                $rewardVisitCount = $rewardVisitRet['visitCount'] + 1;
                if(!is_numeric($updateVisitRet)){
                    Log::write('更新分享奖励浏览数失败cid'.$cid.'|sql:'.$shareRewardVisit_tab->getLastSql());
                    return false;
                }
            }else{
                Log::write('浏览数4444');
                $rewardVisitCount = $rewardVisitRet['visitCount'];
            }
        }else{
            $rewardVisitData = [];
            $rewardVisitData['cid'] = $cid;
            $rewardVisitData['uid'] = $miUid;
            $rewardVisitData['module'] = 'micontent';
            $rewardVisitData['moduleId'] = $moduleId;
            $rewardVisitData['rewardId'] = $rewardId;
            $rewardVisitData['visitCount'] = 1;
            $rewardVisitData['createTime'] = date('Y-m-d H:i:s');
            $visitSaveRet = $shareRewardVisit_tab->add($rewardVisitData);
            Log::write('浏览数2222:'.$cid.'|sql:'.$shareRewardVisit_tab->getLastSql());
            if(!$visitSaveRet){
                Log::write('保存奖励浏览数失败cid:'.$cid.'|sql:'.$shareRewardVisit_tab->getLastSql());
                return false;
            }
            $rewardVisitCount = 1;
        }

        if(empty($rewardCfg['isShare'])){
            return true;
        }

        //单篇还是多篇
        if($rewardCfg['articleNum']){
            $rewardVisitCount = $shareRewardVisit_tab->where(['rewardId'=>$rewardId,'cid'=>$cid, 'uid'=>$miUid,
                'module'=>'micontent'])->sum('visitCount');
        }
        if(!$rewardCfg['isShare']){
            return true;
        }
        //如果达标就判断此时是否已经产生了获奖记录,如果没有,就新增一条获奖记录
        foreach($rewardCfg['shareRewardCfg'] as $key=>$val){
            if($rewardVisitCount >= $val['visitCount'] && $val['shareRemainder']>0){
                $rewardRetMap = [];
                $rewardRetMap['rewardId'] = $rewardId;
                $rewardRetMap['cid'] = $cid;
                $rewardRetMap['module'] = 'micontent';
                if(!$rewardCfg['articleNum']){
                    $rewardRetMap['moduleId'] = $moduleId;
                }
                $rewardRetMap['uid'] = $miUid;
                $rewardRetMap['rewardGrade'] = $val['rewardGrade'];
                $rewardRetMap['rewardCause'] = 1;//奖励原因
                if($shareRewardRet->where($rewardRetMap)->getField('id')){
                    //此等级奖励结果已经生成
                    continue;
                }else{
                    M()->startTrans();
                    $val['articleNum'] = $rewardCfg['articleNum'];
                    $val['endTime'] = $rewardCfg['endTime'];
                    $val['moduleId'] = $moduleId;
                    $val['currentUid'] = $currentUid;//导致产生奖励的uid
                    $rewardRetMap['moduleId'] = $moduleId;
                    $rewardRetMap['rewardName'] = $rewardCfg['name'];
                    $rewardRetMap['rewardGrade'] = $val['rewardGrade'];
                    $rewardRetMap['rewardJson'] = json_encode($val);
                    $rewardRetMap['rewardCause'] = 1;
                    $rewardRetMap['rewardWay'] = $val['rewardType'];
                    $rewardRetMap['shareVisitNum'] = $rewardVisitCount;
                    $rewardRetMap['createTime'] = date('Y-m-d H:i:s');
                    $saveRet = $shareRewardRet->add($rewardRetMap);
                    if(!$saveRet){
                        Log::write('分享奖励生成记录失败cid:'.$cid.'|sql:'.$shareRewardRet->getLastSql());
                        return false;
                    }
                    $updateCfgRet = $shareRewardSet_tab->where(['id'=>$val['id']])->save([
                        'shareRemainder'=>$val['shareRemainder']-1
                    ]);
                    if(!$updateCfgRet){
                        M()->rollback();
                        Log::write('分享奖励更新剩余份数失败cid:'.$cid.'|sql:'.$shareReward_tab->getLastSql());
                        return false;
                    }
                    M()->commit();
                    if($val['rewardType'] == 1){
                        self::shareRewardMoneyGift($cid, $miUid,$val['redMoney'],$val['blessings'],$rewardId,$saveRet,
                            $moduleId);
                    }else{
                        //直接推送模板消息
                        $sql = 'select userName from wx_'.$cid.'_user where id='.$miUid;
                        $miUidOpenid = M()->query($sql);
                        $templateRedId = $TemplateModel->where(['status'=>'shareRewardClueConfirm'])->getField('templateId');
                        if(!$templateRedId){
                            Log::write('reward无效的模板id'.$TemplateModel->getLastSql());
                        }
                        $customer = WeixinApi::getCustomer();
                        if($customer['mode']&&$customer['grantStatus']){
                            $domainName = $customer["appid"];
                            $http['RESOURCEURL']="http://".$domainName.".".C('NEWSERVER_HOST');
                        }else{
                            $http['RESOURCEURL'] = C("SERVER_HOST");

                        }
                        //
                        $urls = $http['RESOURCEURL']."call.html?customerId=".$cid."&module=micontent&method=getRewardInfo&params=%7B%22micontentId%22%3A%22".$moduleId."%22%2C%22rewardId%22%3A%22".$rewardId."%22%7D";
                        $data['first'] = array('value'=> '恭喜您,获得奖励礼品一份','color'=>"#743A3A");
                        $data['keyword1'] = array('value'=> $rewardCfg['name'],'color'=>'#173177');	//活动
                        $data['keyword2'] = array('value'=> $val['clueGiftName'],'color'=>'#173177');//奖品					//奖品
                        $data['keyword3'] = array('value'=> date('Y-m-d'),'color'=>'#173177');					//领取时间
                        $data['remark'] = array('value'=>'点击提交领取信息',"color"=>'#008000');
                        $url = urlencode($urls);
                        $topcolor = "#FF0000";
                        WeixinApi::sendTpl($miUidOpenid[0]['userName'], $templateRedId, $url,$topcolor,$data,true,$cid);
                    }
                }
            }
        }
        return true;
    }

    /**
     * 产生奖励时发送奖励
     * @param null $cid     //customerId
     * @param $miUid        //获奖人uid
     * @param $redMoney     //红包金额
     * @param $blessings    //红包祝福语
     * @param $rewardId     //奖励配置id
     * @param $rewardRetId      //奖励结果id
     * @param $moduleId         //关联奖励的模块id
     * @param $rewardType         //0:分享,1:线索
     */
    static public function shareRewardMoneyGift($cid=null,$miUid,$redMoney,$blessings,$rewardId,$rewardRetId,$moduleId,
                                                $rewardType=0){
        Log::write('tiaoshi000');
        if(!$cid){
            $cid = Session::$user['customerId'];
        }
        Session::switchCustomer(0);
        $shareRewardRet = M('share_reward_result');
        $CustomerMallSettingModel = D('customer_mall_setting');
        $cutomerUser_tab = M('customer_user');
        Session::switchCustomer($cid);
        $template_tab = M('template_messages');

        M()->startTrans();
        //红包发送成功需要将状态改为已发送
        $updateRewardRet = $shareRewardRet->where(['id'=>$rewardRetId])->save(['status'=>1,'grantTime'=>date('Y-m-d H:i:s')]);
        if(!$updateRewardRet){
            if($rewardType){
                Log::write('更新基于奖励状态失败cid:'.$cid.'|uid:'.$miUid.'|sql:'.$shareRewardRet->getLastSql());
                Output::instance()->object([
                    'code'=>-1,
                    'msg'=>'更新奖励状态失败',
                    'results'=>[]
                ]);
                return;
            }
            Log::write('发送红包更新状态失败cid:'.$cid.'|sql:'.$shareRewardRet->getLastSql());
            return false;
        }
        $customer = WeixinApi::getCustomer($cid);
        if(!$customer['mode'] && !$customer['grantStatus']){
           $customer['nick_name'] = $cutomerUser_tab->where(['customerId'=>$cid, 'agent'=>'business'])->getField('fullName');
        }
        if(strlen($customer['nick_name']) > 32){
            $customer['nick_name'] = mb_substr($customer['nick_name'], 0, 9, 'utf-8').'...';
        }
        $userInfoSql = 'SELECT a.userName,b.nickname FROM wx_'.$cid.'_user a LEFT JOIN wx_'.$cid.'_user_weixin_info b on a.id=b.userId WHERE ( a.id = '.$miUid.' ) LIMIT 1  ';
        $miUserInfo = M()->query($userInfoSql);
        if(!$miUserInfo[0]['userName']){
            Log::write('winnerInfo:'.M()->getLastSql());
        }
        /*($send_name,$openid,$amount,$wishing,$printErr = false,$partnerkey='',$mch_id='',$wxappid='',*/
        $wxPayInfo = $CustomerMallSettingModel->where(['customerId'=>$cid])->find();
        $partnerkey = '';
        $mch_id = '';
        $wxappid = '';
        if($wxPayInfo){
            $partnerkey = $wxPayInfo['payKey'];
            $mch_id = $wxPayInfo['mchId'];
            $wxappid = $wxPayInfo['appId'];
        }
        $sendRet = WeixinApi::sendRedEnvelopeByOpenId($customer['nick_name'],$miUserInfo[0]['userName'],
            $redMoney,$blessings,false,$partnerkey,$mch_id,$wxappid);
        if(!$sendRet){
            M()->rollback();
            if($rewardType){
                Log::write('基于线索发送红包失败cid:'.$cid.'|uId:'.$miUid.'|sql:'.M()->getLastSql());
                return false;
            }
            Log::write('分享奖励发送红包失败.$cid:'.$cid.'|uid:'.$miUid.'|rewardId:'.$rewardId.'|mallName:'.$customer['nick_name'].'|sql:'.M()->getLastSql());
            return false;
        }
        M()->commit();
        $templateId = $template_tab->where(['status'=>'shareRewardConfirm'])->getField('templateId');
        if(empty($templateId)){
            Log::write('模板id不存在:'.$cid.'|sql:'.$template_tab->getLastSql());
        }

        if($customer['mode']&&$customer['grantStatus']){
            $domainName = $customer["appid"];
            $http['RESOURCEURL']="http://".$domainName.".".C('NEWSERVER_HOST');
        }else{
            $http['RESOURCEURL'] = C("SERVER_HOST");
        }

        $urls = $http['RESOURCEURL']."call.html?customerId=".$cid."&module=micontent&method=getRewardInfo&params=%7B%22micontentId%22%3A%22".$moduleId."%22%2C%22rewardId%22%3A%22".$rewardId."%22%7D";
        $data['first'] = array('value'=> '您的奖励已发放','color'=>"#743A3A");
        $data['keyword1'] = array('value'=> $miUserInfo[0]['nickname'],'color'=>'#173177');	//领取人
        $data['keyword2'] = array('value'=> '红包奖励'.$redMoney.'元','color'=>'#173177');					//奖品
        $data['keyword3'] = array('value'=> date('Y-m-d'),'color'=>'#173177');					//领取时间
        $data['remark'] = array('value'=>'点击查看奖励详情',"color"=>'#008000');
        $url = urlencode($urls);
        $topcolor = "#FF0000";
        WeixinApi::sendTpl($miUserInfo[0]['userName'], $templateId, $url,$topcolor,$data,true,$cid);
        return true;
    }
}